/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cv4j.app.slice;

import ohos.aafwk.content.Intent;
import ohos.agp.components.Image;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Texture;
import ohos.agp.utils.Color;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Position;

import com.cv4j.app.ResourceTable;
import com.cv4j.app.app.BaseAbilitySlice;
import com.cv4j.core.binary.ConnectedAreaLabel;
import com.cv4j.core.binary.ContourAnalysis;
import com.cv4j.core.binary.Threshold;
import com.cv4j.core.datamodel.ByteProcessor;
import com.cv4j.core.datamodel.CV4JImage;
import com.cv4j.core.datamodel.MeasureData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 轮廓分析(CA)
 *
 * @since 2021-05-17
 */
public class ContourAnalysisAbilitySlice extends BaseAbilitySlice {
    final int colorsize = 255;
    private Image image0;
    private Image image1;
    private Image image2;
    private Image image3;

    @Override
    protected int getUIContentLayoutId() {
        return ResourceTable.Layout_ability_contour_analysis;
    }

    @Override
    protected void initComponents(Intent intent) {
        image0 = (Image) findComponentById(ResourceTable.Id_image0);
        image1 = (Image) findComponentById(ResourceTable.Id_image1);
        image2 = (Image) findComponentById(ResourceTable.Id_image2);
        image3 = (Image) findComponentById(ResourceTable.Id_image3);
        image0.setPixelMap(ResourceTable.Media_test_ca);

        CV4JImage cv4jimage = new CV4JImage(image0.getPixelMap());
        Threshold threshold = new Threshold();
        threshold.process((ByteProcessor) cv4jimage.convert2Gray().getProcessor(),
            Threshold.THRESH_OTSU, Threshold.METHOD_THRESH_BINARY, colorsize);
        image1.setPixelMap(cv4jimage.getProcessor().getImage().toBitmap());

        ConnectedAreaLabel connectedAreaLabel = new ConnectedAreaLabel();
        connectedAreaLabel.setFilterNoise(true);
        int[] mask = new int[cv4jimage.getProcessor().getWidth() * cv4jimage.getProcessor().getHeight()];
        connectedAreaLabel.process((ByteProcessor) cv4jimage.getProcessor(), mask, null, false);
        Map<Integer, Integer> colors = new HashMap<>();
        Random random = new Random();
        int height = cv4jimage.getProcessor().getHeight();
        int width = cv4jimage.getProcessor().getWidth();
        int size = height * width;
        for (int indext = 0; indext < size; indext++) {
            int col = mask[indext];
            if (col >= 0) {
                colors.put(col, Color.argb(colorsize, random.nextInt(colorsize),
                    random.nextInt(colorsize), random.nextInt(colorsize)));
            }
        }
        cv4jimage.resetBitmap();
        PixelMap newBitmap = cv4jimage.getProcessor().getImage().toBitmap();
        for (int row = 0; row < height; row++) {
            for (int col = 0; col < width; col++) {
                int cols = mask[row * width + col];
                if (cols >= 0) {
                    newBitmap.writePixel(new Position(col, row), colors.get(cols));
                }
            }
        }
        image2.setPixelMap(newBitmap);
        initImage3(newBitmap, cv4jimage, mask);
    }

    private void initImage3(PixelMap newBitmap, CV4JImage cv4jimage, int[] mask) {
        PixelMap.InitializationOptions options = new PixelMap.InitializationOptions();
        options.size = newBitmap.getImageInfo().size;
        PixelMap thirdBitmap = PixelMap.create(newBitmap, options);
        ContourAnalysis ca = new ContourAnalysis();
        List<MeasureData> measureDatas = new ArrayList<>();
        ca.process((ByteProcessor) cv4jimage.convert2Gray().getProcessor(), mask, measureDatas);
        Canvas canvas = new Canvas(new Texture(thirdBitmap));
        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setTextSize(12);
        for (MeasureData data : measureDatas) {
            canvas.drawText(paint, data.toString(), data.getCp().x1, data.getCp().y1);
        }
        image3.setPixelMap(thirdBitmap);
    }
}
